//
//  TLS_DestinationVC.m
//  Travel_World
//
//  Created by lanou on 15/10/12.
//  Copyright © 2015年 TLS. All rights reserved.
//

#import "TLS_DestinationVC.h"
#import "QTAFNnetWorkTool.h"
#import "UIImageView+WebCache.h"
#import "MRDestinationCollectionReusableView.h"
#import "MRDestinationCollectionViewCell.h"
#import "MRDestinationTableViewCell.h"
#import "MRDestinationFooterCollectionReusableView.h"
#import "MRDestinationModel.h"
#import "MRCityViewController.h"
#import "MRCountryViewController.h"

NSInteger countryIndex = 0;

@interface TLS_DestinationVC ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *collectionViewArr;

@property (nonatomic, strong) NSMutableArray *tableViewArr;

@property (nonatomic, strong) NSMutableArray *array;

@end

@implementation TLS_DestinationVC

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.layer.masksToBounds = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_login"]];
    self.navigationController.navigationBar.translucent = NO;
    
    self.title = @"目的地";
    
    self.tabBarController.tabBar.hidden = NO;
}

//- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
//{
//    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
//    if (self) {
//        
//        self.collectionViewArr = [NSMutableArray array];
//        
//        self.tableViewArr = [NSMutableArray array];
//        
//    }
//    return self;
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self createData];
    
    [self createTableView];
    
    [self createCollectionView];
    
    [self createButton];
    
}

#pragma mark 数据解析
- (void)createData
{
    [QTAFNnetWorkTool getUrl:@"http://open.qyer.com/qyer/footprint/continent_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&page=1&track_app_channel=App%2520Store&track_app_version=6.6&track_device_info=iPad%2520Air%2520%28Wifi%29&track_deviceid=A24310D6-4784-474E-86CE-81D543A1EB8A&track_os=ios" body:nil hudSuperView:self.view result:QTJSON headerFile:nil success:^(id result) {
        
        self.array = [NSMutableArray array];
        
        self.collectionViewArr = [NSMutableArray array];
        
        self.tableViewArr = [NSMutableArray array];
        
        self.array = [MRDestinationModel baseModelByArr:result[@"data"]];
        
        self.collectionViewArr = [MRDestinationModel baseModelByArr:result[@"data"][countryIndex][@"hot_country"]];
        
        self.tableViewArr = [MRDestinationModel baseModelByArr:result[@"data"][countryIndex][@"country"]];
        
        [self.collectionView reloadData];
        [self.tableView reloadData];

        
    }];
}

#pragma mark 创建tableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT- 49) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
}

#pragma mark tableView的区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.tableViewArr.count != 0) {
        return 1;
    }
    return 0;
}

#pragma mark tableView的cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.tableViewArr.count != 0) {
        return self.tableViewArr.count;
    }
    return 0;
}

#pragma mark 创建tableView的cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.tableViewArr.count > indexPath.row) {
        
        static NSString *reuse = @"reuse";
        MRDestinationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        //    if (self.tableViewArr.count > indexPath.row) {
        
        if (!cell) {
            cell = [[MRDestinationTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
        }
        
        MRDestinationModel *model = self.tableViewArr[indexPath.row];
        
        cell.cnname.text = model.cnname;
        
        cell.enname.text = model.enname;
        
        //    }
        return cell;

        
    }
    
    return nil;
//    static NSString *reuse = @"reuse";
//    MRDestinationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
////    if (self.tableViewArr.count > indexPath.row) {
//    
//        if (!cell) {
//            cell = [[MRDestinationTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
//        }
//        
//        MRDestinationModel *model = self.tableViewArr[indexPath.row];
//        
//        cell.cnname.text = model.cnname;
//        
//        cell.enname.text = model.enname;
//        
////    }
//    return cell;
}

#pragma mark tableView的点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.tableViewArr.count > indexPath.row) {
        
        if ([[self.tableViewArr[indexPath.item] label] isEqualToString:@"旅行地"]) {
            
            MRCityViewController *cityVC = [[MRCityViewController alloc] init];
            
            NSString *url = [NSString stringWithFormat:@"http://open.qyer.com/qyer/footprint/city_detail?city_id=%@&client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&lat=38.88261036070509&lon=121.5397574228773&oauth_token=55d7f8a1931dedc7d5a8f24ab63426d0&page=1&track_app_channel=App%%2520Store&track_app_version=6.7&track_device_info=iPhone5%%2C4&track_deviceid=41AE760B-510C-4778-AF4D-177B387E0F3B&track_os=ios%%25209.0.2&track_user_id=6852801&v=1",[self.tableViewArr[indexPath.row] Id].description];
            
            cityVC.url = url;
            
            [self.navigationController pushViewController:cityVC animated:YES];
            
        } else if ([[self.tableViewArr[indexPath.row] label] isEqualToString:@"城市"]) {
            
            MRCountryViewController *countryVC = [[MRCountryViewController alloc] init];
            
            NSString *url = [NSString stringWithFormat:@"http://open.qyer.com/qyer/footprint/country_detail?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&country_id=%@&lat=38.88261036070509&lon=121.5397574228773&oauth_token=55d7f8a1931dedc7d5a8f24ab63426d0&page=1&track_app_channel=App%%2520Store&track_app_version=6.7&track_device_info=iPhone5%%2C4&track_deviceid=41AE760B-510C-4778-AF4D-177B387E0F3B&track_os=ios%%25209.0.2&track_user_id=6852801&v=1",[self.tableViewArr[indexPath.row] Id].description];
            
            countryVC.url = url;
            
            [self.navigationController pushViewController:countryVC animated:YES];
            
        }
    }

    
}

#pragma mark 创建collectionView
- (void)createCollectionView
{
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(170 * WID, 250 * HEI);
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 10 * WID, 0, 10 * HEI);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(20 * WID, 0, WIDTH, HEI * 2.15 * 667 - 49) collectionViewLayout:flowLayout];
    [self.view addSubview:self.collectionView];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    self.collectionView.bounces = NO;
    
    self.tableView.tableHeaderView = self.collectionView;
    
    // 注册collectionView的cell
    [self.collectionView registerClass:[MRDestinationCollectionViewCell class] forCellWithReuseIdentifier:@"collectionViewCell"];
    
    // 注册collectionView的头视图
    [self.collectionView registerClass:[MRDestinationCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"collectionViewHeaderView"];
    flowLayout.headerReferenceSize = CGSizeMake(0, 290 * HEI);
    
    [self.collectionView registerClass:[MRDestinationFooterCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"collectionViewFooterView"];
    flowLayout.footerReferenceSize = CGSizeMake(0, 60 * HEI);
    
}

#pragma mark collectionView的headerView
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        MRDestinationCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"collectionViewHeaderView" forIndexPath:indexPath];
        
//        view.backgroundColor = [UIColor Color];
        
//        MRDestinationModel *model = self.array[indexPath.row];
        
//        view.hotDestination.text = [NSString stringWithFormat:@"%@热门目的地",[self.array[countryIndex] cnname]];
        
        view.hotDestination.text = [NSString stringWithFormat:@"%@热门目的地",[self.array[countryIndex] cnname]];
        
        return view;
    } if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        MRDestinationFooterCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"collectionViewFooterView" forIndexPath:indexPath];
        
        view.otherDestination.text = [NSString stringWithFormat:@"%@其他目的地",[self.array[countryIndex] cnname]];
        
        return view;
    } else {
        
        return nil;
        
    }
}

#pragma mark collectionView的cell的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.collectionViewArr.count;
}

#pragma mark 创建collectionView的cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.collectionViewArr.count > indexPath.row) {
        MRDestinationCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionViewCell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor redColor];
        
        
        MRDestinationModel *model = self.collectionViewArr[indexPath.row];
        
        [cell.countryImageView sd_setImageWithURL:[NSURL URLWithString:model.photo]placeholderImage:[UIImage imageNamed:@"placeholder"]];
        
        cell.countLabel.text = model.count.description;
        
        cell.cityLabel.text = model.label;
        
        cell.cnCountryLabel.text = model.cnname;
        
        cell.enCountryLabel.text = model.enname;

        
        if (cell.countLabel.text.length > 2) {
            
            NSDictionary *fontDic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:23],NSFontAttributeName, nil];
            CGRect rect = [cell.countLabel.text boundingRectWithSize:CGSizeMake(170, 30) options:NSStringDrawingUsesLineFragmentOrigin attributes:fontDic context:nil];
            
            cell.cityCountView.frame = CGRectMake(WID * (170 - 35) - rect.size.width, 15 * HEI , rect.size.width + 20 * WID, 60 * HEI);
            
            cell.countLabel.frame = CGRectMake(0, 0, rect.size.width + 10, 35 * HEI);
            
            cell.cityLabel.frame = CGRectMake(0, 35 * HEI, rect.size.width + 10, 20 * HEI);
            
            
        } else  if (cell.countLabel.text.length <= 2) {
            
            NSDictionary *fontDic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15],NSFontAttributeName, nil];
            
            CGRect rect = [cell.cityLabel.text boundingRectWithSize:CGSizeMake(170, 30) options:NSStringDrawingUsesLineFragmentOrigin attributes:fontDic context:nil];
            
            cell.cityCountView.frame = CGRectMake(WID * (170 - 35) - rect.size.width, 15 * HEI , rect.size.width + 20 * WID, 60 * HEI);
            
            cell.countLabel.frame = CGRectMake(0, 0, rect.size.width + 10, 35 * HEI);
            
            cell.cityLabel.frame = CGRectMake(0, 35 * HEI, rect.size.width + 10, 20 * HEI);
            
        }
        
        return cell;
        
    } else {
        
        return nil;
        
    }
    
 
}

#pragma mark collectionView的点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.collectionViewArr.count > indexPath.item) {
        
        if ([[self.collectionViewArr[indexPath.item] label] isEqualToString:@"旅行地"]) {
            
            MRCityViewController *cityVC = [[MRCityViewController alloc] init];
            
            NSString *url = [NSString stringWithFormat:@"http://open.qyer.com/qyer/footprint/city_detail?city_id=%@&client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&lat=38.88261036070509&lon=121.5397574228773&oauth_token=55d7f8a1931dedc7d5a8f24ab63426d0&page=1&track_app_channel=App%%2520Store&track_app_version=6.7&track_device_info=iPhone5%%2C4&track_deviceid=41AE760B-510C-4778-AF4D-177B387E0F3B&track_os=ios%%25209.0.2&track_user_id=6852801&v=1",[self.collectionViewArr[indexPath.item] Id].description];
            
            cityVC.url = url;
            
            [self.navigationController pushViewController:cityVC animated:YES];
            
        } else if ([[self.collectionViewArr[indexPath.item] label] isEqualToString:@"城市"]) {
            
            MRCountryViewController *countryVC = [[MRCountryViewController alloc] init];
            
            NSString *url = [NSString stringWithFormat:@"http://open.qyer.com/qyer/footprint/country_detail?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&country_id=%@&lat=38.88261036070509&lon=121.5397574228773&oauth_token=55d7f8a1931dedc7d5a8f24ab63426d0&page=1&track_app_channel=App%%2520Store&track_app_version=6.7&track_device_info=iPhone5%%2C4&track_deviceid=41AE760B-510C-4778-AF4D-177B387E0F3B&track_os=ios%%25209.0.2&track_user_id=6852801&v=1",[self.collectionViewArr[indexPath.item] Id].description];
            
            countryVC.url = url;
            
            [self.navigationController pushViewController:countryVC animated:YES];
            
        }
    }
}

#pragma mark 创建map的button
- (void)createButton
{
    
    //亚洲
    UIButton * asiaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    asiaButton.tag = 1000;
    asiaButton.titleLabel.font = [UIFont systemFontOfSize:14];
    asiaButton.backgroundColor = [UIColor grayColor];
    [asiaButton setTitle:@"亚洲" forState:UIControlStateNormal];
    asiaButton.layer.cornerRadius = 5;
    asiaButton.frame = CGRectMake(100 * WID, 90 * HEI, 40 * WID, 25 * HEI);
    [asiaButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.collectionView addSubview:asiaButton];
    
    //欧洲
    UIButton * EuropeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    EuropeButton.tag = 1001;
    EuropeButton.titleLabel.font = [UIFont systemFontOfSize:14];
    EuropeButton.backgroundColor = [UIColor grayColor];
    [EuropeButton setTitle:@"欧洲" forState:UIControlStateNormal];
    EuropeButton.layer.cornerRadius = 5;
    EuropeButton.frame = CGRectMake( 55 * WID, 55 * HEI, 40 * WID, 25 * HEI);
    [EuropeButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.collectionView addSubview:EuropeButton];
    
    //北美洲
    UIButton * NorthAmericaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    NorthAmericaButton.tag = 1002;
    NorthAmericaButton.backgroundColor = [UIColor grayColor];
    [NorthAmericaButton setTitle:@"北美洲" forState:UIControlStateNormal];
    NorthAmericaButton.layer.cornerRadius = 5;
    NorthAmericaButton.frame = CGRectMake( 250 * WID, 60 * HEI, 55 * WID, 25 * HEI);
    [NorthAmericaButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    NorthAmericaButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.collectionView addSubview:NorthAmericaButton];
    
    //南美洲
    UIButton*SouthAmericaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    SouthAmericaButton.tag = 1003;
    SouthAmericaButton.backgroundColor = [UIColor grayColor];
    [SouthAmericaButton setTitle:@"南美洲" forState:UIControlStateNormal];
    SouthAmericaButton.layer.cornerRadius = 5;
    SouthAmericaButton.frame = CGRectMake(320 * WID, 150 * HEI, 55 * WID, 25 * HEI);
    SouthAmericaButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [SouthAmericaButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.collectionView addSubview:SouthAmericaButton];
    
    //大洋洲
    UIButton*OceaniaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    OceaniaButton.tag = 1004;
    OceaniaButton.backgroundColor = [UIColor grayColor];
    [OceaniaButton setTitle:@"大洋洲" forState:UIControlStateNormal];
    OceaniaButton.titleLabel.font = [UIFont systemFontOfSize:14];
    OceaniaButton.layer.cornerRadius = 5;
    OceaniaButton.frame = CGRectMake(130 * WID, 150 * HEI, 55 * WID, 25 * HEI);
    [OceaniaButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.collectionView addSubview:OceaniaButton];
    
    //非洲
    UIButton * AfricaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    AfricaButton.tag = 1005;
    AfricaButton.backgroundColor = [UIColor grayColor];
    [AfricaButton setTitle:@"非洲" forState:UIControlStateNormal];
    AfricaButton.layer.cornerRadius = 5;
    AfricaButton.titleLabel.font = [UIFont systemFontOfSize:14];
    AfricaButton.frame = CGRectMake(30 * WID, 130 * HEI, 40 * WID, 25 * HEI);
    [AfricaButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.collectionView addSubview:AfricaButton];
    
    //南极洲
    UIButton * AntarcticaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    AntarcticaButton.tag = 1006;
    AntarcticaButton.backgroundColor = [UIColor grayColor];
    [AntarcticaButton setTitle:@"南极洲" forState:UIControlStateNormal];
    AntarcticaButton.titleLabel.font = [UIFont systemFontOfSize:14];
    AntarcticaButton.layer.cornerRadius = 5;
    AntarcticaButton.frame = CGRectMake(200 * WID, 200 * HEI, 55 * WID, 25 * HEI);
    [AntarcticaButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.collectionView addSubview:AntarcticaButton];
    
}

#pragma mark button的点击方法
-(void)buttonClick:(UIButton*)button{
    switch (button.tag) {
        case 1000:
            countryIndex=0;
            break;
        case 1001:
            countryIndex=1;
            break;
        case 1002:
            countryIndex=2;
            break;
        case 1003:
            countryIndex=3;
            break;
        case 1004:
            countryIndex=4;
            break;
        case 1005:
            countryIndex=5;
            break;
        case 1006:
            countryIndex=6;
            break;
        default:
            break;
    }
 
    [self.tableView reloadData];
    
    [self.collectionView reloadData];
    
    [self createData];
    
//    [self createCollectionView];
    
//    [self.tableView reloadData];
//    
//    [self.collectionView reloadData];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
